package com.hospital.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hospital.system.dao.DepartmentDao;
import com.hospital.system.dao.SysRoleUserTableDao;
import com.hospital.system.entity.SysRoleUserTable;
import com.hospital.system.model.Department;
import com.hospital.system.service.SysRoleUserTableService;
import com.hospital.system.util.BCryptPasswordEncoderUtil;
import com.hospital.system.dao.SysUserMapper;
import com.hospital.system.entity.SysUserEntity;
import com.hospital.system.service.SysUserService;
import com.hospital.system.vo.SysUserVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * 用户服务
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {

    @Autowired
    BCryptPasswordEncoderUtil bCryptPasswordEncoderUtil;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private DepartmentDao departmentDao;
    //用户激活状态
    private static final int USER_STATE = 1;

    /**
     * 通过账号查询用户
     *
     * @param username
     * @return
     */
    @Override
    public SysUserEntity getUserByUserName(String username) {
        LambdaQueryWrapper<SysUserEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询条件：全匹配账号名，和状态为1的账号
        lambdaQueryWrapper
                .eq(SysUserEntity::getUserName, username)
                .eq(SysUserEntity::getState, USER_STATE);

        //用getOne查询一个对象出来
        SysUserEntity user = this.getOne(lambdaQueryWrapper);

        return user;
    }

    /**
     * 个性化验证登录
     *
     * @param username    账号
     * @param rawPassword 原始密码
     * @return
     */
    @Override
    public boolean checkLogin(String username, String rawPassword) throws Exception {
        SysUserEntity userEntity = this.getUserByUserName(username);
        System.out.println("userEntity = " + userEntity);
        if (userEntity == null) {
            //System.out.println("checkLogin--------->账号不存在，请重新尝试！");
            //设置友好提示
            throw new Exception("账号不存在，请重新尝试！");
        } else {
            //加密的密码
            String encodedPassword = userEntity.getPassWord();
            //和加密后的密码进行比配
            if (!bCryptPasswordEncoderUtil.matches(rawPassword, encodedPassword)) {
                //System.out.println("checkLogin--------->密码不正确！");
                //设置友好提示
                throw new Exception("密码不正确！");
            } else {
                return true;
            }
        }
    }

    /**
     * 注册
     *
     * @param sysUserVo
     * @return
     * @throws Exception
     */
    @Override
    public boolean register(SysUserVo sysUserVo) throws Exception {
        if (sysUserVo != null) {

            SysUserEntity f = this.getUserByUserName(sysUserVo.getName());
            System.out.println("f:" + f);
            if (f != null) {
                throw new Exception("这个用户已经存在，不能重复。");
            }

            //保存到数据库
            System.out.println("po:" + this.voToPo(sysUserVo));
            return this.save(this.voToPo(sysUserVo));
        } else {
            throw new Exception("错误消息：用户对象为空！");
        }
    }

    /**
     * VO到PO的转换
     *
     * @param vo
     * @return
     */
    public SysUserEntity voToPo(SysUserVo vo) {
        SysUserEntity po = new SysUserEntity();
        System.out.println("vo:" + vo);
        if (null != vo) {
            if(!StringUtils.isBlank(vo.getId())){
                po.setUserId(vo.getId());
            }
            if(!StringUtils.isBlank(vo.getName())){
                po.setUserName(vo.getName());
            }
            if(!StringUtils.isBlank(vo.getBirthday())){
                SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    po.setBirthday(format1.parse(vo.getBirthday()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            po.setBirthday(new Date(vo.getBirthday()));
//            LocalDateTime ofInstant = LocalDateTime.ofInstant(Instant.parse(vo.getBirthday()), ZoneId.of("+0800"));
//            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//            // String format = dtf2.format(ofInstant);
            if(!StringUtils.isBlank(vo.getDepartmentCode()))
                po.setDepartmentCode(vo.getDepartmentCode());
            if(!StringUtils.isBlank(vo.getEmail()))
                po.setEmail(vo.getEmail());
            if(!StringUtils.isBlank(vo.getPhone()))
                po.setPhone(vo.getPhone());
            if(!StringUtils.isBlank(vo.getPassw()))
                po.setPlainPassword(vo.getPassw());
            if(!StringUtils.isBlank(vo.getSex()))
                po.setSex(vo.getSex());
            if(!StringUtils.isBlank(vo.getWorkAddress()))
                po.setWorkAddress(vo.getWorkAddress());
            if(!StringUtils.isBlank(vo.getPassw()))
                //对密码进行加密
                po.setPassWord(bCryptPasswordEncoderUtil.encode(vo.getPassw()));
            //设置状态为1
            if(null != vo.getState())
                po.setState(vo.getState());
        }
        System.out.println("po:" + po);
        return po;
    }

    public SysUserVo poToVo(SysUserEntity po) {
        SysUserVo vo = new SysUserVo();
        if (null != po) {
            vo.setId(po.getUserId());
            vo.setName(po.getUserName());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (null != po.getBirthday())
                vo.setBirthday(sdf.format(po.getBirthday()));
            if (null != po.getCreateTime())
                vo.setCreateTime(sdf2.format(po.getCreateTime()));
            if (!StringUtils.isBlank(po.getPhone()))
                vo.setPhone(po.getPhone());
            if (!StringUtils.isBlank(po.getEmail()))
                vo.setEmail(po.getEmail());
            if (!StringUtils.isBlank(po.getEmail()))
                vo.setSex(po.getSex());

            vo.setPassw(po.getPlainPassword());

            vo.setState(po.getState());
            if (!StringUtils.isBlank(po.getDepartmentCode()))
                vo.setDepartmentCode(po.getDepartmentCode());
            if (!StringUtils.isBlank(po.getWorkAddress()))
                vo.setWorkAddress(po.getWorkAddress());
            List<String> roleNames = sysUserMapper.getRoleNameByUserId(po.getUserId());
            for(String roleName : roleNames)
                vo.setRoleName(roleName);
            if (!StringUtils.isBlank(po.getDepartmentCode())) {
                Department department = departmentDao.selectDepartmentByCode(po.getDepartmentCode());
                if (null != department)
                    vo.setDepartment(department.getName());
            }
            return vo;
        }
        return null;
    }
}
